<?php

header('Expires: ' . gmdate("D, d M Y H:i:s", time() + 60*60*24*10) . ' GMT');
header('Last-Modified: ' . gmdate("D, d M Y H:i:s", time()) . ' GMT');

$f = $_GET['f'];
$w = @$_GET['w'];
$h = @$_GET['h'];
$watermark = @$_GET['wm'];

$base = dirname(__FILE__);
$path = $base . "/" . $f;

if (! is_file($path)) {
    $path = dirname(__FILE__) . '/noimage.png';
}
$ext  = strtolower(substr($path, strrpos($path, ".")+1));

$img = new Imagick($path);
$geo = $img->getImageGeometry();
$w0 = $geo['width'];
$h0 = $geo['height'];

if ($w || $h) {
	if ($w && $h) {
		$img->scaleimage($w, $h, true);
	} else {
		$img->scaleimage($w, $h);
	}
} else if (!$watermark) {
    $img = file_get_contents($path);
}

if ($watermark) {
    $wm = new Imagick($base . '/watermark.png');
    $imgGeo = $img->getImageGeometry();
    $wmGeo  = $wm->getImageGeometry();
    
    $w2 = $imgGeo['width'] * 0.4;
    $h2 = $w2 * $wmGeo['height'] / $wmGeo['width'];
    $wm->scaleImage($w2, $h2);
    $wmGeo  = $wm->getImageGeometry();
    
    $x = $imgGeo['width'] - $wmGeo['width'];
    $y = $imgGeo['height'] - $wmGeo['height'];
    $img->compositeimage($wm, Imagick::COMPOSITE_OVER, $x, $y);
}

header("Content-Type: image/{$ext}");
echo $img;

?>
